package com.mynews.test;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.mynews.R;
import com.mynews.utils.StringUtils;

/**
 * Created by Administrator on 2017/6/28.
 */

public class MyRefreshRecyclerView extends RecyclerView {
    private static final String TAG = MyRefreshRecyclerView.class.getSimpleName();
    private View headRefreshView;
    private View footLoadMoreView;
    private Context mContext;
    private ImageView iv_arrow;
    private TextView tv_refresh, tv_refresh_time;
    private ProgressBar pb_bar;
    private int headRefreshViewHeight; //整个下拉刷新的高度
    private float startY = -1;//滑动初始值
    private int currentStatue = 0;
    private static final int PULL_REFRESH = 1;
    private static final int RELEASE_REFRESH = 2;
    private static final int REFRESHING = 3;
    private LinearLayoutManager layoutManager;
    private RotateAnimation upAnima;
    private RotateAnimation downAnima;


    public MyRefreshRecyclerView(Context context) {
        this(context, null);
    }

    public MyRefreshRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyRefreshRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        init();
    }

    private void init() {
        initAnimation();
        initHeadRefreshView();
        initFootRefreshView();
    }

    private void initHeadRefreshView() {
        headRefreshView = LayoutInflater.from(mContext).inflate(R.layout.item_head_flush, null);
        iv_arrow = (ImageView) headRefreshView.findViewById(R.id.iv_arrow);
        tv_refresh = (TextView) headRefreshView.findViewById(R.id.tv_refresh);
        tv_refresh_time = (TextView) headRefreshView.findViewById(R.id.tv_refresh_time);
        pb_bar = (ProgressBar) headRefreshView.findViewById(R.id.pb_bar);

        tv_refresh_time.setText("上次刷新："+StringUtils.currentDate());
        //这两行是为了保证能够获得headRefreshView的高度的写法
        headRefreshView.measure(0, 0);
        headRefreshViewHeight = headRefreshView.getMeasuredHeight();
        Log.e(TAG, "initHeadRefreshView: : " + headRefreshViewHeight);
//        headRefreshView.setPadding(0,-headRefreshViewHeight,0,0);//初始化隐藏
        RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, -headRefreshViewHeight, 0, 0);
        headRefreshView.setLayoutParams(layoutParams);


    }


    public boolean isScrollToTop() {
        return !canScrollVertically(-1);
    }


    /**
     * 手动判断是否滑动到底部
     * @return computeVerticalScrollExtent屏幕显示该view的高度  computeVerticalScrollOffset：划过的距离  computeVerticalScrollRange：view的高度
     */
    //RecyclerView.canScrollVertically(1)的值表示是否能向上滚动，false表示已经滚动到底部
    //RecyclerView.canScrollVertically(-1)的值表示是否能向下滚动，false表示已经滚动到顶部
//    public  boolean isSlideToBottom() {
//        if (this.computeVerticalScrollExtent() + this.computeVerticalScrollOffset()
//                >= this.computeVerticalScrollRange()){
//            return true;
//        }
//        return false;
//    }

    /**
     * 是否到顶部
     *
     * @return
     */
    private boolean isSlideToTop() {
        if (layoutManager == null) {
            layoutManager = (LinearLayoutManager) getLayoutManager();
        }
        if (layoutManager.findFirstCompletelyVisibleItemPosition() == 1 || layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 刷新状态改变时的动画
     */
    private void initAnimation() {
//        从下拉刷新状态转换为释放刷新状态
        upAnima = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        upAnima.setFillAfter(true);
        upAnima.setDuration(500);
//         转到下拉刷新的动画
        downAnima = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        downAnima.setFillAfter(true);
        downAnima.setDuration(500);
    }

    /**
     * 是否到底部
     *
     * @return
     */
    private boolean isSlideToBottom() {
        if (layoutManager == null) {
            layoutManager = (LinearLayoutManager) getLayoutManager();
        }
        if (layoutManager.findFirstCompletelyVisibleItemPosition() == getChildCount() - 1) {
            return true;
        }
        return false;
    }


    @Override
    public boolean onTouchEvent(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = e.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (startY == -1) {
                    startY = e.getY();
                }
                float dy = e.getY() - startY;
                Log.e(TAG, "onTouchEvent: dy:" + dy + " getY():" + getY());
//                Log.e(TAG, "onTouchEvent: paddingTop canScrollVertically："+canScrollVertically(-1));
                if (currentStatue == REFRESHING) {
                    break;
                }
                //如果滚动到了顶部 开始执行下拉刷新
                if (isSlideToTop()) {
                    if (dy > 0) {
                        int paddingTop = (int) (dy - headRefreshViewHeight);
                        if (paddingTop < 0 && currentStatue != PULL_REFRESH) {
                            currentStatue = PULL_REFRESH;
                            setHeadViewStatue();
                        } else if (paddingTop > 0 && currentStatue != RELEASE_REFRESH) {
                            currentStatue = RELEASE_REFRESH;
                            setHeadViewStatue();
                        }
                        Log.e(TAG, "onTouchEvent: paddingTop:" + paddingTop);
                        setMargin(headRefreshView, paddingTop);
                    }
                }else {//执行底部上拉加载更多
                    if(isSlideToBottom()){

                    }
                }

                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                startY = -1;
                if (currentStatue == PULL_REFRESH) {
                    setMargin(headRefreshView, -headRefreshViewHeight);
                } else if (currentStatue == RELEASE_REFRESH) {
                    setMargin(headRefreshView, 0);
                    currentStatue = REFRESHING;
                    setHeadViewStatue();
                }
                break;
        }
        return super.onTouchEvent(e);
    }

    private void setMargin(View view, int marginTop) {
        RecyclerView.LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
        layoutParams.setMargins(0, marginTop, 0, 0);
        view.requestLayout();
    }





    private void setHeadViewStatue() {
        switch (currentStatue) {
            case REFRESHING:
                tv_refresh.setText("正在刷新...");
                iv_arrow.setVisibility(INVISIBLE);
                pb_bar.setVisibility(VISIBLE);
                if(refreshClick != null){
                    refreshClick.refreshing();
                }
                break;
            case RELEASE_REFRESH:
                tv_refresh.setText("释放刷新...");
                iv_arrow.setVisibility(VISIBLE);
                pb_bar.setVisibility(INVISIBLE);
                iv_arrow.setRotation(180);
                break;
            case PULL_REFRESH:
                tv_refresh.setText("下拉刷新...");
                iv_arrow.setVisibility(VISIBLE);
                pb_bar.setVisibility(GONE);
                iv_arrow.setRotation(0);
                break;
        }
    }

    private void initFootRefreshView() {

    }

    public View getFootLoadMoreView() {
        return footLoadMoreView;
    }

    public View getHeadRefreshView() {
        return headRefreshView;
    }

    public void setRefreshClick(RefreshClick refreshClick) {
        this.refreshClick = refreshClick;
    }

    private RefreshClick refreshClick;
    public interface RefreshClick{
        void refreshing();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            setMargin(headRefreshView, -headRefreshViewHeight);
            currentStatue = PULL_REFRESH;
            setHeadViewStatue();
            handler.removeMessages(0);
        }
    };

    public void refreshFinish(boolean isSuccess){
        if(isSuccess){
            tv_refresh_time.setText("上次刷新："+StringUtils.currentDate());
        }
        handler.sendEmptyMessageDelayed(0,3000);
    }

}
